import { _decorator, Component, Node } from 'cc';
import { CatAction } from './CatAction';
import { PinAction } from './PinAction';
import { LevelAction } from './LevelAction';
import { DataModel } from './DataModel';
import { Global } from './Global';
const { ccclass, property } = _decorator;

@ccclass('LayerCatAction')
export class LayerCatAction extends Component {

    allLayer_arrs:PinAction[][] 
    catActions :CatAction[] =[]
    /** type PinAction */
    batteryBoxs = []
    bBox:any = null;

    static Inst: LayerCatAction = null;

    onLoad(): void {
        LayerCatAction.Inst = this

        for (let i = 0; i < this.node.children.length; i++) {
            const cat = this.node.children[i].getComponent(CatAction);
            this.catActions.push(cat)
        }
    }
    start() {

    }


    //根据钉子的颜色按顺序插入对应的位置，放入上面孔
    public put_pin(pin: PinAction): boolean {
        let can_move_arr: CatAction[] = [];
        this.node.children.forEach(slot => {
            if (slot.getComponent(CatAction).check_able_put(pin)) {
                can_move_arr.push(slot.getComponent(CatAction));
            }
        });

        let target: CatAction = null;
        can_move_arr.forEach(element => {
            if (!target) {
                target = element;
            } else {
                console.log("can_move_arr", element.get_temp_hole_num(), target.get_temp_hole_num())
                if (element.get_temp_hole_num() < target.get_temp_hole_num()) {
                    target = element;
                }
            }

        });
        if (target) {
            //放入上面孔
            return target.put_pin(pin, "LayerSolot");
        }
        return false;
    }

    public init_cat() {
        // --->改 25.7.9.18.11
        console.log("获取所有电池id")
        this.layer_pinNum(2);//刚开始生成 2个仓

        this.catActions.forEach(element => {
            element?.init_cat()
        });

    }

    /** 获取电池仓颜色 和 多余的个数 */
    public get_pin_residue(){
        let arr:{color:any ; num:number}[] = [];
        this.node.children.forEach(slot => {
            let cat = slot.getComponent(CatAction)
            if (cat) {
                let pin_color = cat.get_cat_color();
                let residue = cat.get_temp_hole_num();
                let val:{color:any ; num:number} = {color:null , num:0};
                if (pin_color) {
                    console.log(pin_color, " 剩余数：", residue)
                    val.color = pin_color;
                    val.num = residue;

                    console.log(" *** single电池仓：",val)
                    arr.push(val)
                }
                else{
                    console.log("未定义")
                }
            }
        });
        console.log(arr)
        return arr;
    }

    public get_cat_color_arr() {
        let arr = [];
        this.node.children.forEach(slot => {
            if (slot.getComponent(CatAction)) {
                let color = slot.getComponent(CatAction).get_cat_color();
                if (color) {
                    arr.push(color);
                }
            }
        });
        return arr;
    }

    // --->改 25.7.9.18.11 获取所有layer
    public layer_pinNum(get_num =  1) {

        console.log("电池仓逻辑：1.如果颜色种类>=2，box取此随机颜色; 2.如果一种类型数量>=3，box取此颜色; 3.如果上两点不满足，往下层推，加起来算")

        console.log("需要进行剔除！！！ ， 1.剔除 this.batteryBoxs 显示的电池仓 ， 2.空白电池仓 和 锤子锤掉的 电池")

        //if(!this.allLayer_arrs)
            this.allLayer_arrs = LevelAction.Inst.get_pin_color_allLayer();

        let arrs = this.allLayer_arrs;

        let dcBoxs = []

        let _arr = [];
        let _allnum = 0;
        for (let i = 0; i < arrs.length; i++) {
            let temp_arr = []
            for (let j = 0; j < arrs[i].length; j++) {
                temp_arr.push(arrs[i][j].pin_color.id)
            }
            temp_arr.sort();
            _arr.push(temp_arr.length)
            _allnum += temp_arr.length
        }
        console.log("电池:", _arr)
        console.log("总数：", _allnum)

        console.log(arrs)

        for (let i = 0; i < get_num; i++) {
            console.log("--------------------------------------------------------")
            this.remove_add_becoming(arrs, dcBoxs);
            dcBoxs = this.runArr(arrs, dcBoxs )
            console.log("--------------------------------------------------------\n\n--------------------------------------------------------\n\n")
        }
        

        console.log("dcBoxs : ", dcBoxs)

        console.log("逻辑判断结束")

        this.batteryBoxs = dcBoxs;
    }

    /** 剔除和添加合适的（1.获取 临时仓电池 锤子隐藏的电池 2.获取所有层级电池 3.移除 颜色电池仓） */
    remove_add_becoming(arrs: any[][] , dcBoxs: any[]){

        let new_dcBoxs = dcBoxs.slice()

        //移除 颜色电池仓
        let upCang_end = false;
        let upCang = this.get_pin_residue();

        console.log("*** 上面仓 ：",upCang.length)
        if (upCang.length > 0) {
            for (let i = 0; i < arrs.length; i++) {
                let arri = arrs[i];
                for (let j = 0; j < arri.length; j++) {
                    let arrj_color = arri[j].pin_color;
                    let _color = upCang[0].color
                    console.log("*** 颜色: ",arrj_color , _color)
                    if (_color.id == arrj_color.id && upCang[0].num > 0) {
                        console.log(" *** 剔除:",j,arri,arrs)
                        arri.splice(j, 1)
                        console.log(" *** 剔除后:",arri,arrs)
                        j--
                        upCang[0].num--;
                        if (upCang[0].num <= 0) {
                            upCang.splice(0, 1)
                            if (upCang.length <= 0) {
                                upCang_end = true;
                                break;
                            }
                            i = 0;
                        }
                    }
                }
                if (upCang_end) {
                    break;
                }
            }
        }
        console.log("upCang 剔除后：",arrs)

        
        let dcBox_end = false;
        let dcBox_num = 3;
        console.log(" *** 临时储存数组: ",arrs)
        console.log(" *** 如果只获取一个 length 是为0",new_dcBoxs.length)
        if(new_dcBoxs.length > 0){
            console.log(new_dcBoxs)
            for (let i = 0; i < arrs.length; i++) {
                let arri = arrs[i];
                console.log(arri)
                for (let j = 0; j < arri.length; j++) {
                    let arrj_color = arri[j].pin_color;
                    let _id = new_dcBoxs[0].id
                    console.log(arrj_color.id)
                    console.log(_id)
                    console.log(dcBox_num)
                    if (_id == arrj_color.id && dcBox_num > 0) {
                        console.log(" *** 剔除:",j,arri)
                        arri.splice(j, 1)
                        console.log(" *** 剔除后:",arri)
                        j--
                        dcBox_num--;
                        if (dcBox_num <= 0) {
                            new_dcBoxs.splice(0, 1)
                            if (new_dcBoxs.length <= 0) {
                                dcBox_end = true;
                                break;
                            }
                            i = 0;
                        }
                    }
                }
                if (dcBox_end) {
                    break;
                }
            }
        }
        console.log(" *** ",arrs)

        //获取 临时仓电池 锤子隐藏的电池
        let temp_cang = Global.layer_empty_action.get_pin_arr();//PinAction pin_color colorDate
        let hide_cang = Global.bucket_action.get_pin_arr();
        temp_cang = temp_cang.concat(hide_cang);


        for (let i = 0; i < arrs.length; i++) {
            if(arrs[i].length <= 0){
                arrs.splice(i,1)
            }
        }
        if(temp_cang.length > 0){
            //应该加入 第一层 ，而不是新建一个第一层放到最前面
            //arrs.unshift(temp_cang)
            for (let i = 0; i < temp_cang.length; i++) {
                const element = temp_cang[i];
                arrs[0].push(element)
            }
        }

    }

    /**
     * 生成电池仓 每次只获取一个
     * @param arrs 每层电池
     * @param dcBoxs 电池仓(colorDate)
     */
    runArr(arrs: any[][], dcBoxs: any[] ) {
        console.log(arrs, dcBoxs)

        let _dcBoxs: any[] = []

        /** 临时 */
        let lay_add_arr = []
        let meet = false;

        /** 往下层加 只判断类型大于2 剔除 */
        let type_remove_val = 0;
        let type_remove_id = -1;

        for (let i = 0; i < arrs.length; i++) {

            if(!meet){//如果不满足，往下层加
                lay_add_arr = lay_add_arr.concat(arrs[i])
                lay_add_arr.sort();

                //------------------- 已找到 cur_type >= 2 的颜色，直接往下层找到3个，剔除结束
                if (type_remove_val > 0) {
                    let sp_num = type_remove_val;
                    for (let a = 0; a < lay_add_arr.length; a++) {//剔除此类型3个
                        const b = lay_add_arr[a];
                        if (b.pin_color.id == type_remove_id) {
                            lay_add_arr.splice(a, 1)
                            a--;
                            console.log("移除", b)
                            sp_num--;
                            if (sp_num <= 0) {
                                break;
                            }
                        }
                    }
                    //没剔除完 3个
                    if (sp_num > 0) {
                        type_remove_val = sp_num
                        
                        continue
                    }
                    else{
                        break
                    }
                }
                //-------------------

            }
            else{
                i--//满足，再判断此层级
                meet = false

                break;//一次只获取一个
            }

            //console.log("看这里 ---> ",lay_add_arr)

            let temp_arr = []
            for (let j = 0; j < lay_add_arr.length; j++) {
                temp_arr.push(lay_add_arr[j].pin_color.id)
            }
            //temp_arr.sort();
            console.log("电池arr:", temp_arr)

            let cur_type = 0;
            let num_arr = [];
            let num_arr_id = [];
            let judge_id = -1;
            let temp_val = 1
            for (let k = 0; k < temp_arr.length; k++) {
                const id = temp_arr[k];
                if (judge_id != id) {
                    cur_type++;
                    if (judge_id != -1) {
                        num_arr.push(temp_val)
                        num_arr_id.push(id)

                        if (k == temp_arr.length - 1) {
                            num_arr.push(1)
                            num_arr_id.push(id)
                        }
                    }

                    judge_id = id
                    temp_val = 1;
                }
                else {
                    temp_val++;

                    if (k == temp_arr.length - 1) {
                        num_arr.push(temp_val)
                        num_arr_id.push(id)
                    }
                }
            }

            

            if (cur_type >= 2) {//类型大于2
                let val1 = Math.floor(Math.random() * lay_add_arr.length)

                let model = lay_add_arr[val1].pin_color//colorDate
                _dcBoxs.push(model)

                console.log("随机值：", val1, model)

                let sp_num = 3;
                for (let a = 0; a < lay_add_arr.length; a++) {//剔除此类型3个
                    const b = lay_add_arr[a];
                    if (b.pin_color.id == model.id) {
                        lay_add_arr.splice(a, 1)
                        a--;
                        console.log("移除", b)
                        sp_num--;
                        if (sp_num <= 0) {
                            break;
                        }
                    }
                }
                //没剔除完 3个
                if(sp_num > 0){
                    type_remove_val = sp_num
                    type_remove_id = model.id
                }
                else {
                    meet = true;
                }
                    continue
            }

            
            let color_id = -1
            /** 大于3 */
            let isDy3 = false;
            for (let n = 0; n < num_arr.length; n++) {
                if (num_arr[n] >= 3) {//数量大于3
                    color_id = num_arr_id[n]
                    isDy3 = true;
                }

            }
            let sp_num = 3;
            if (color_id >= 0) {
                for (let a = 0; a < lay_add_arr.length; a++) {
                    const pin = lay_add_arr[a].pin_color;
                    if (color_id == pin.id) {
                        if(isDy3){
                            _dcBoxs.push(pin)
                            isDy3=false;
                        }

                        lay_add_arr.splice(a, 1)
                        a--;
                        console.log("移除", pin.id)
                        sp_num--;
                        if (sp_num <= 0) {
                            break;
                        }
                    }
                }
                meet = true;
                break;
            }



        }

        console.log("temp_dcBoxs : ",_dcBoxs)

        dcBoxs = dcBoxs.concat(_dcBoxs)
        console.log("dcBoxs: ",dcBoxs)

        return dcBoxs
    }

}

